
import React, { useEffect, useRef, useState, useCallback } from 'react';
import * as pdfjsLib from 'pdfjs-dist';
import { Button } from '@/components/ui/button';
import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card';
import { ChevronLeft, ChevronRight, ZoomIn, ZoomOut, BookOpen, ScrollText } from 'lucide-react';
import { getUrlParam, addUrlParam } from '@/utils/urlUtils';

// 设置PDF.js worker - 使用jsdelivr CDN 5.4.296版本
pdfjsLib.GlobalWorkerOptions.workerSrc = 'https://cdn.jsdelivr.net/npm/pdfjs-dist@5.4.296/build/pdf.worker.min.mjs';

const PdfViewer = ({ fileUrl, fileName }) => {
  const canvasRef = useRef(null);
  const containerRef = useRef(null);
  const scrollContainerRef = useRef(null);
  const [pdf, setPdf] = useState(null);
  const [currentPage, setCurrentPage] = useState(1);
  const [totalPages, setTotalPages] = useState(0);
  const [scale, setScale] = useState(1.0);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState(null);
  const [processedFileUrl, setProcessedFileUrl] = useState('');
  const [viewMode, setViewMode] = useState('scroll'); // 默认改为滚动模式
  const [renderedPages, setRenderedPages] = useState(new Map());
  const pageRefs = useRef(new Map());
  const renderingPages = useRef(new Set());
  const scrollTimeoutRef = useRef(null);
  const isLoadingRef = useRef(false);
  const [scrollCurrentPage, setScrollCurrentPage] = useState(1);
  const lastLoadedPageRef = useRef(0);

  // 预处理fileUrl，添加accessToken参数
  useEffect(() => {
    console.log('=== PdfViewer fileUrl预处理开始 ===');
    console.log('原始fileUrl:', fileUrl);
    
    if (!fileUrl) {
      console.log('fileUrl为空，跳过预处理');
      setProcessedFileUrl('');
      return;
    }
    
    const accessToken = getUrlParam('accessToken');
    console.log('从页面URL获取的accessToken:', accessToken);
    
    let finalFileUrl = fileUrl;
    
    if (accessToken) {
      console.log('检测到accessToken，开始拼接到fileUrl');
      finalFileUrl = addUrlParam(fileUrl, 'accessToken', accessToken);
      console.log('拼接accessToken后的fileUrl:', finalFileUrl);
    } else {
      console.log('未检测到accessToken，使用原始fileUrl');
    }
    
    setProcessedFileUrl(finalFileUrl);
    console.log('=== PdfViewer fileUrl预处理完成 ===');
    console.log('最终处理后的fileUrl:', finalFileUrl);
  }, [fileUrl]);

  // 检测当前页码的函数
  const detectCurrentPage = useCallback(() => {
    if (viewMode !== 'scroll') {
      console.log('页码检测跳过 - 非滚动模式');
      return;
    }

    console.log('=== 开始页码检测 ===');
    console.log('当前渲染的页面数量:', renderedPages.size);
    console.log('总页数:', totalPages);
    console.log('pageRefs数量:', pageRefs.current.size);

    const viewportCenter = window.innerHeight / 2;
    console.log('视口中心位置:', viewportCenter);

    let closestPage = 1;
    let minDistance = Infinity;

    pageRefs.current.forEach((element, pageNumber) => {
      if (element) {
        const rect = element.getBoundingClientRect();
        const pageCenter = rect.top + rect.height / 2;
        const distance = Math.abs(pageCenter - viewportCenter);

        console.log(`页面 ${pageNumber}: top=${rect.top}, height=${rect.height}, center=${pageCenter}, distance=${distance}`);

        if (distance < minDistance) {
          minDistance = distance;
          closestPage = pageNumber;
        }
      }
    });

    console.log('检测到最近的页面:', closestPage, '距离:', minDistance);
    console.log('=== 页码检测完成 ===');
    
    if (closestPage !== scrollCurrentPage) {
      console.log(`页码更新: ${scrollCurrentPage} -> ${closestPage}`);
      setScrollCurrentPage(closestPage);
    }
  }, [viewMode, renderedPages, totalPages, scrollCurrentPage]);

  // 检查并加载后续页面的函数
  const checkAndLoadNextPages = useCallback(() => {
    if (!pdf || viewMode !== 'scroll') {
      return;
    }

    console.log('=== 检查是否需要加载更多页面 ===');
    console.log('当前页码:', scrollCurrentPage);
    console.log('最后加载的页码:', lastLoadedPageRef.current);
    console.log('总页数:', totalPages);

    const loadedAfterCurrent = lastLoadedPageRef.current - scrollCurrentPage;
    console.log('当前页后已加载页数:', loadedAfterCurrent);

    if (loadedAfterCurrent < 15 && lastLoadedPageRef.current < totalPages) {
      const pagesToLoad = Math.min(15 - loadedAfterCurrent, totalPages - lastLoadedPageRef.current);
      console.log(`需要加载 ${pagesToLoad} 页`);

      for (let i = 1; i <= pagesToLoad; i++) {
        const pageNumber = lastLoadedPageRef.current + i;
        if (pageNumber <= totalPages) {
          console.log(`准备加载页面 ${pageNumber}`);
          renderSinglePage(pageNumber);
        }
      }

      lastLoadedPageRef.current = Math.min(lastLoadedPageRef.current + pagesToLoad, totalPages);
      console.log('更新最后加载页码为:', lastLoadedPageRef.current);
    } else {
      console.log('无需加载更多页面');
    }
  }, [pdf, viewMode, scrollCurrentPage, totalPages]);

  // 滚动监听，检测当前页码并触发加载
  useEffect(() => {
    if (viewMode !== 'scroll') {
      console.log('滚动监听未启动 - 非滚动模式');
      return;
    }

    console.log('=== 启动滚动监听 ===');
    console.log('监听目标: window');

    const handleScroll = () => {
      console.log('滚动事件触发 - scrollY:', window.scrollY);

      if (scrollTimeoutRef.current) {
        clearTimeout(scrollTimeoutRef.current);
      }

      scrollTimeoutRef.current = setTimeout(() => {
        console.log('滚动停止，开始检测页码');
        detectCurrentPage();
        checkAndLoadNextPages();
      }, 100);
    };

    window.addEventListener('scroll', handleScroll, { passive: true });
    console.log('滚动监听已添加到window');

    // 初始检测一次
    setTimeout(() => {
      console.log('执行初始页码检测');
      detectCurrentPage();
    }, 500);

    return () => {
      console.log('=== 移除滚动监听 ===');
      window.removeEventListener('scroll', handleScroll);
      if (scrollTimeoutRef.current) {
        clearTimeout(scrollTimeoutRef.current);
      }
    };
  }, [viewMode, detectCurrentPage, checkAndLoadNextPages]);

  // 键盘事件监听
  useEffect(() => {
    const handleKeyDown = (event) => {
      if (viewMode === 'page') {
        if (event.key === 'ArrowRight') {
          goToNextPage();
        } else if (event.key === 'ArrowLeft') {
          goToPrevPage();
        }
      }
    };

    window.addEventListener('keydown', handleKeyDown);
    
    return () => {
      window.removeEventListener('keydown', handleKeyDown);
    };
  }, [currentPage, totalPages, viewMode]);

  useEffect(() => {
    if (processedFileUrl) {
      console.log('processedFileUrl已准备就绪，开始加载PDF');
      loadPdf();
    }
  }, [processedFileUrl]);

  useEffect(() => {
    if (pdf) {
      if (viewMode === 'page') {
        renderPage();
      }
    }
  }, [pdf, currentPage, scale, viewMode]);

  // 滚动模式下初始化加载前15页
  useEffect(() => {
    if (pdf && viewMode === 'scroll') {
      console.log('滚动模式初始化，开始加载前15页');
      setRenderedPages(new Map());
      renderingPages.current.clear();
      setScrollCurrentPage(1);
      lastLoadedPageRef.current = 0;
      
      const pagesToLoad = Math.min(15, totalPages);
      console.log(`初始加载 ${pagesToLoad} 页`);
      
      for (let i = 1; i <= pagesToLoad; i++) {
        renderSinglePage(i);
      }
      
      lastLoadedPageRef.current = pagesToLoad;
      console.log('初始加载完成，最后加载页码:', lastLoadedPageRef.current);
    }
  }, [pdf, viewMode, scale, totalPages]);

  // 渲染单个页面
  const renderSinglePage = async (pageNumber) => {
    if (!pdf) {
      console.log(`页面 ${pageNumber}: PDF未加载`);
      return;
    }
    
    if (renderedPages.has(pageNumber)) {
      console.log(`页面 ${pageNumber}: 已渲染，跳过`);
      return;
    }

    if (renderingPages.current.has(pageNumber)) {
      console.log(`页面 ${pageNumber}: 正在渲染中，跳过`);
      return;
    }

    renderingPages.current.add(pageNumber);
    console.log(`页面 ${pageNumber}: 开始渲染`);

    try {
      const page = await pdf.getPage(pageNumber);
      const viewport = page.getViewport({ scale: 1 });
      
      const toolbarHeight = 64;
      const availableHeight = window.innerHeight - toolbarHeight;
      const availableWidth = window.innerWidth;
      
      const scaleX = availableWidth / viewport.width;
      const scaleY = availableHeight / viewport.height;
      const autoScale = Math.min(scaleX, scaleY, 1);
      
      const scaledViewport = page.getViewport({ scale: autoScale * scale });
      
      const canvas = document.createElement('canvas');
      const context = canvas.getContext('2d');
      
      canvas.height = scaledViewport.height;
      canvas.width = scaledViewport.width;
      
      const renderContext = {
        canvasContext: context,
        viewport: scaledViewport
      };
      
      await page.render(renderContext).promise;
      
      console.log(`页面 ${pageNumber}: 渲染完成，立即显示`);
      
      setRenderedPages(prev => {
        const newMap = new Map(prev);
        newMap.set(pageNumber, {
          pageNumber: pageNumber,
          canvas: canvas
        });
        return newMap;
      });
      
    } catch (err) {
      console.error(`页面 ${pageNumber} 渲染失败:`, err);
    } finally {
      renderingPages.current.delete(pageNumber);
      console.log(`页面 ${pageNumber}: 渲染状态清除`);
    }
  };

  const loadPdf = async () => {
    try {
      console.log('=== 开始加载PDF ===');
      console.log('使用的文件URL:', processedFileUrl);
      
      setLoading(true);
      setError(null);
      
      const loadingTask = pdfjsLib.getDocument(processedFileUrl);
      const pdfDoc = await loadingTask.promise;
      
      console.log('PDF加载成功，页数:', pdfDoc.numPages);
      setPdf(pdfDoc);
      setTotalPages(pdfDoc.numPages);
      setLoading(false);
    } catch (err) {
      console.error('PDF加载失败:', err);
      console.error('失败的URL:', processedFileUrl);
      setError('PDF文件加载失败，请检查文件链接是否有效');
      setLoading(false);
    }
  };

  const renderPage = async () => {
    if (!pdf || !canvasRef.current) return;

    try {
      const page = await pdf.getPage(currentPage);
      const viewport = page.getViewport({ scale: 1 });
      
      const toolbarHeight = 64;
      const availableHeight = window.innerHeight - toolbarHeight;
      const availableWidth = window.innerWidth;
      
      const scaleX = availableWidth / viewport.width;
      const scaleY = availableHeight / viewport.height;
      const autoScale = Math.min(scaleX, scaleY, 1);
      
      const scaledViewport = page.getViewport({ scale: autoScale * scale });
      
      const canvas = canvasRef.current;
      const context = canvas.getContext('2d');
      
      canvas.height = scaledViewport.height;
      canvas.width = scaledViewport.width;
      
      const renderContext = {
        canvasContext: context,
        viewport: scaledViewport
      };
      
      await page.render(renderContext).promise;
    } catch (err) {
      console.error('页面渲染失败:', err);
      setError('页面渲染失败');
    }
  };

  const goToPrevPage = () => {
    if (currentPage > 1) {
      setCurrentPage(currentPage - 1);
    }
  };

  const goToNextPage = () => {
    if (currentPage < totalPages) {
      setCurrentPage(currentPage + 1);
    }
  };

  const zoomIn = () => {
    console.log('放大视图，清空渲染状态');
    setScale(scale * 1.2);
    if (viewMode === 'scroll') {
      setRenderedPages(new Map());
      renderingPages.current.clear();
      isLoadingRef.current = false;
      lastLoadedPageRef.current = 0;
    }
  };

  const zoomOut = () => {
    console.log('缩小视图，清空渲染状态');
    setScale(scale / 1.2);
    if (viewMode === 'scroll') {
      setRenderedPages(new Map());
      renderingPages.current.clear();
      isLoadingRef.current = false;
      lastLoadedPageRef.current = 0;
    }
  };

  const toggleViewMode = () => {
    const newMode = viewMode === 'page' ? 'scroll' : 'page';
    console.log('切换视图模式:', viewMode, '->', newMode);
    setViewMode(newMode);
    if (newMode === 'scroll') {
      console.log('切换到滚动模式，清空渲染状态');
      setRenderedPages(new Map());
      renderingPages.current.clear();
      isLoadingRef.current = false;
      setScrollCurrentPage(1);
      lastLoadedPageRef.current = 0;
    }
  };

  if (loading) {
    return (
      <div className="flex items-center justify-center min-h-screen">
        <div className="text-center">
          <div className="animate-spin rounded-full h-12 w-12 border-b-2 border-blue-600 mx-auto mb-4"></div>
          <p className="text-gray-600">正在加载PDF文件...</p>
          <div className="mt-2 text-xs text-gray-400">
            <p>文件URL: {processedFileUrl}</p>
          </div>
        </div>
      </div>
    );
  }

  if (error) {
    return (
      <div className="flex items-center justify-center min-h-screen">
        <Card className="w-96">
          <CardHeader>
            <CardTitle className="text-red-600">加载失败</CardTitle>
          </CardHeader>
          <CardContent>
            <p className="text-gray-600 mb-4">{error}</p>
            <Button onClick={loadPdf} className="w-full">
              重新加载
            </Button>
            <div className="mt-4 text-xs text-gray-400">
              <p>调试信息:</p>
              <p>原始URL: {fileUrl}</p>
              <p>处理后URL: {processedFileUrl}</p>
              <p>accessToken: {getUrlParam('accessToken') || '未找到'}</p>
            </div>
          </CardContent>
        </Card>
      </div>
    );
  }

  return (
    <div className="min-h-screen bg-gray-100 flex flex-col">
      {viewMode === 'page' ? (
        <div 
          ref={containerRef}
          className="flex-1 flex items-center justify-center overflow-auto"
        >
          <canvas
            ref={canvasRef}
            className="shadow-lg mb-16"
            style={{
              maxWidth: '100%',
              maxHeight: '100%',
              height: 'auto',
              width: 'auto'
            }}
          />
        </div>
      ) : (
        <div className="flex-1 pb-20">
          <div className="flex flex-col items-center space-y-4 py-4">
            {Array.from({ length: totalPages }, (_, index) => {
              const pageNumber = index + 1;
              const pageData = renderedPages.get(pageNumber);
              
              return (
                <div 
                  key={pageNumber} 
                  ref={(el) => {
                    if (el) {
                      pageRefs.current.set(pageNumber, el);
                      console.log(`页面 ${pageNumber} ref已设置`);
                    }
                  }}
                  className="shadow-lg bg-white"
                  style={{
                    minHeight: pageData ? 'auto' : '800px',
                    display: 'flex',
                    flexDirection: 'column',
                    alignItems: 'center',
                    justifyContent: 'center'
                  }}
                >
                  {pageData ? (
                    <canvas
                      ref={(el) => {
                        if (el && pageData.canvas) {
                          el.width = pageData.canvas.width;
                          el.height = pageData.canvas.height;
                          const ctx = el.getContext('2d');
                          ctx.drawImage(pageData.canvas, 0, 0);
                        }
                      }}
                    />
                  ) : (
                    <div className="flex items-center justify-center h-full">
                      <div className="text-center">
                        <div className="animate-spin rounded-full h-8 w-8 border-b-2 border-blue-600 mx-auto mb-2"></div>
                        <p className="text-sm text-gray-500">等待加载...</p>
                      </div>
                    </div>
                  )}
                  <div className="text-center py-2 text-sm text-gray-600">
                    第 {pageNumber} 页
                  </div>
                </div>
              );
            })}
          </div>
        </div>
      )}
      
      <div className="fixed bottom-0 left-0 right-0 bg-white shadow-lg border-t z-50">
        <div className="w-full px-4 py-3">
          <div className="flex items-center justify-between">
            <div className="flex items-center space-x-2">
              <Button
                variant={viewMode === 'scroll' ? 'default' : 'outline'}
                size="sm"
                onClick={toggleViewMode}
                title={viewMode === 'scroll' ? '滚动模式' : '翻页模式'}
              >
                {viewMode === 'page' ? (
                  <BookOpen className="h-4 w-4" />
                ) : (
                  <ScrollText className="h-4 w-4" />
                )}
              </Button>

              {viewMode === 'page' ? (
                <>
                  <div className="border-l pl-2 ml-2">
                    <Button
                      variant="outline"
                      size="sm"
                      onClick={goToPrevPage}
                      disabled={currentPage <= 1}
                    >
                      <ChevronLeft className="h-4 w-4" />
                    </Button>
                    
                    <span className="text-sm text-gray-600 px-3">
                      {currentPage} / {totalPages}
                    </span>
                    
                    <Button
                      variant="outline"
                      size="sm"
                      onClick={goToNextPage}
                      disabled={currentPage >= totalPages}
                    >
                      <ChevronRight className="h-4 w-4" />
                    </Button>
                  </div>
                </>
              ) : (
                <div className="border-l pl-2 ml-2">
                  <span className="text-sm text-gray-600 px-3">
                    当前页: {scrollCurrentPage} / {totalPages}
                  </span>
                </div>
              )}
              
              <div className="border-l pl-2 ml-2">
                <Button
                  variant="outline"
                  size="sm"
                  onClick={zoomOut}
                >
                  <ZoomOut className="h-4 w-4" />
                </Button>
                
                <span className="text-sm text-gray-600 px-3">
                  {Math.round(scale * 100)}%
                </span>
                
                <Button
                  variant="outline"
                  size="sm"
                  onClick={zoomIn}
                >
                  <ZoomIn className="h-4 w-4" />
                </Button>
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>
  );
};

export default PdfViewer;

